import * as  Koa from "koa"
import * as http from "http"
import * as path from "path";
import * as mongoose from "mongoose";

import * as koaBody from "koa-body"
import * as KoaStatic from 'koa-static';
import * as WebSocket from "ws";
import websocketApi from "./controllers/message"


import * as ip from "ip"
import {AddressInfo} from "net";

import checkToken from "./middleware/checkToken"

const config = require("./config.json");
const routing = require("./routers");
const serverConfig = {}

function main() {
    const app = new Koa();
    app.state = Object.assign({}, app.state)
    app.use(koaBody({
        multipart: true,
        formidable: {
            uploadDir: path.join(__dirname, "static", "uploads"),
            keepExtensions: true,
            onFileBegin(name, file) {
                console.log(name, file)
            }
        }
    }))
    app.use(checkToken)
    app.use(KoaStatic(path.join(__dirname, "static")))
    routing(app);
    mongoose.connect(config.db, {});
    const server = http.createServer(app.callback())
    server.on("listening", () => {
        const ipAddress = ip.address()
        const addressInfo = <AddressInfo | null>server.address()
        const port = addressInfo?.port
        app.state.address = `http://${ipAddress}:${port}`
        console.log(`server run at
        local: http://localhost:${port}
        network: http://${ipAddress}:${port}
     `)
    })
    const wss = new WebSocket.Server({
        server
    })
    websocketApi(wss)

    const db = mongoose.connection
    db.on('error', console.error.bind(console, 'connection error:'));
    db.once('open', function () {
        // we're connected!
        console.log('db connected!');
        server.listen(57978)
    });

}

main()
module.exports = {serverConfig}
